import { deviceTreeControllerDeviceTree } from '@/services/ess/deviceTree';
import { TreeDataNode } from 'antd';

export const formatterTree = (combined: TreeDataNode[], unSelectableTypes: string[] = []) => {
  // 创建一个树节点map对象
  const nodeMapping: any = {};
  for (const node of combined) {
    node.children = [];
    node.selectable = !unSelectableTypes
      .map((type) => type.toLowerCase())
      .includes(node.type?.toLowerCase());
    nodeMapping[node.id] = node;
  }
  const tree: TreeDataNode[] = [];
  combined.forEach((node) => {
    if (node.parentId === 0) {
      tree.push(node);
    } else if (nodeMapping[node.parentId]) {
      nodeMapping[node.parentId].children.push(node);
    }
  });
  return tree;
};

export interface deviceTreeData extends API.DeviceTreeVO {
  disableCheckbox?: boolean;
  uniqueId?: string;
}

/**
 * 解析设备树
 * @param treeData
 * @param parent_name
 */
export const formatterDeviceTree = (treeData: deviceTreeData[]): deviceTreeData[] => {
  return treeData.map((item) => {
    item.disableCheckbox = false;
    item.uniqueId = `id${
      item.nodeType === 'AREA'
        ? item.areaId
        : item.nodeType === 'ROOT'
        ? item.stationCode
        : item.deviceCode
    } nodeType${item.nodeType}`;
    if (item.subDevices) {
      item.subDevices = formatterDeviceTree(item.subDevices);
    }
    return item;
  });
};
/**
 * 解析设备树(需要层级节点)
 * @param treeData
 * @param parent_name
 */
export const formatterDeviceTreeHasNode = (
  treeData: deviceTreeData[],
  parent_name = 'ROOT',
): deviceTreeData[] => {
  return treeData.map((item) => {
    item.disableCheckbox = false;
    item.uniqueId = `id${
      item.nodeType === 'AREA'
        ? item.areaId
        : item.nodeType === 'ROOT'
        ? item.stationCode
        : item.deviceCode
    } nodeType${item.deviceType + '' + parent_name}`;
    if (item.subDevices) {
      item.subDevices = formatterDeviceTreeHasNode(item.subDevices, item.deviceName);
    }
    return item;
  });
};

/**
 * 获得维度树
 * @param needGroupNode
 * @param deviceCode
 * @param deviceName
 * @param treeLevel
 * @param deviceTypes
 */
export const getDeviceCascader = (needGroupNode: boolean, treeLevel?: number, deviceTypes = '') => {
  return new Promise((resolve, reject) => {
    deviceTreeControllerDeviceTree({
      needGroupNode: needGroupNode,
      treeLevel: treeLevel,
      deviceTypes: deviceTypes,
    })
      .then((res) => {
        if (res.code === 200) {
          resolve(
            needGroupNode
              ? formatterDeviceTreeHasNode([res.data])
              : formatterDeviceTree([res.data]),
          );
        }
      })
      .catch(() => {
        reject('无数据');
      });
  });
};
